# Copyright (c) 2021-2023 Alibaba Cloud Computing Ltd.
# SPDX-License-Identifier: MulanPSL-2.0

import os
import pyudev
import subprocess
import logging

logger = logging.getLogger('common')

def sysCommand(command: str, cwd: str = "./", log: bool = False):
    '''Run system command with subprocess.run and return result
    '''
    result = subprocess.run(
        command,
        shell=True,
        close_fds=True,
        cwd=cwd,
        stderr=subprocess.PIPE,
        stdout=subprocess.PIPE
    )
    suc = (result.returncode == 0)
    out = result.stdout.decode('UTF-8', 'strict').strip()
    error = result.stderr.decode('UTF-8', 'strict').strip()

    if not suc:
        logger.warning("'{}' return code = {}".format(command, result.returncode))
        raise Exception(error)
    else:
        if log:
            logger.info("{}: {}".format(command, out))
        else:
            logger.debug("{}: {}".format(command, out))
        return out  


def fileAccess(file_path):
    logger.debug("{}: F_OK:{}, R_OK:{}, W_OK:{}".format(
        file_path,
        os.access(file_path,os.F_OK),
        os.access(file_path,os.R_OK),
        os.access(file_path,os.W_OK),
    ))
    return os.access(file_path,os.F_OK) and os.access(file_path,os.R_OK) and os.access(file_path,os.W_OK)


def fileWrite(file_path, data):
    try:
        f = open(file_path,"w")
        f.write(str(data))
        f.close()
    except Exception as e:
        logger.error("writed file: {file_path} error: '{error}'".format(
            file_path = file_path,
            error = e
        ))
    else:
        logger.debug("writed file: {data} -> {file_path}".format(
            data = data,
            file_path = file_path
        ))
    

def listDevice():
    devices = []
    context = pyudev.Context()
    for device in context.list_devices(subsystem="block"):
        if device.device_type == "disk" and device.attributes.get("removable", None) == b"0" and \
                (device.parent is None or \
                device.parent.subsystem in ["scsi", "virtio", "xen"]):
                    devices.append(device.sys_name)
    return devices